import json
import os
import cv2
import shutil
import sys
from PIL import Image, ImageDraw, ImageFont
import chardet
from natsort import ns, natsorted

#拼接输出文件
from config import BASC


def out_name2(basc,name1,back_str,out="output",back='txt'):
    feaa = name1.find('.',2)

    feaas = name1.find('/', 3)
    feaasb=0
    while feaas!=-1:
        feaasb=feaas+1
        feaas = name1.find('/', feaasb)
    # afeaa = feaa + 1
    # feaa2 = name1.find('.',afeaa)
    nmfe = name1[feaasb:feaa]
    fe5 = str(nmfe) + '_'+str(back_str)+"."+back
    if not os.path.exists(f"{basc}/{out}"):
        print("输出文件夹不存在，帮你自动创建好了")
        print("==================================")
        os.mkdir(f"{basc}/{out}")
    fullpath=f'{basc}/{out}/{fe5}'
    return fullpath


#写入文本到文件
def write_file(filename,str1):
    print(f'写入文件')

    fo = open(filename, "w+", encoding='utf-8')
    fo.write(str1)
    fo.close()

#重新形成文本，不删一个字符
def str_transfer1(str_list):
    ann = len(str_list)
    ioo = 0
    print(f'形成文本')
    stryy=None
    for lloo in str_list:
        ioo = ioo + 1
        print("形成拼接文本：" + str(ioo) + "/" + str(ann))
        lloo = str(lloo).replace("\xa0", "")
        lloo = str(lloo).replace("\ufffd", "")
        lloo = str(lloo).replace("\n", "")
        if stryy is None:
            stryy=f'{lloo}\n\n'
        else:
            stryy= f'{stryy}{lloo}\n\n'
    return  stryy

def get_code(filepath):
    with open(filepath,'rb') as f:
        return chardet.detect(f.read())['encoding']

#顺序读取
def read_content_order22(filename):
    print(f'开头读取文本，顺序')

    fk3 = open(filename, "r", encoding=get_code(filename))
    grafk = fk3.readlines()
    fk3.close()

    # print_info(f'开头的处理数组，排序，去掉重复值这些')
    # grafk=no_repeat_list(grafk)

    aaby=[]
    #去掉换行符
    print(f'开头的去掉换行符')
    for ssij in grafk:
        ssij = str(ssij).replace("\n", "")
        ssij = str(ssij).replace(" ", "")
        ssij = str(ssij).replace("　", "")
        if len(ssij)>0:
            aaby.append(ssij)

    # aaby=no_repeat_list(aaby)
    return aaby

#顺序读取
def read_content_order233(filename):
    print(f'开头读取文本，顺序')

    fk3 = open(filename, "r", encoding=get_code(filename))
    grafk = fk3.readlines()
    fk3.close()

    # print_info(f'开头的处理数组，排序，去掉重复值这些')
    # grafk=no_repeat_list(grafk)

    aaby=[]
    #去掉换行符
    print(f'开头的去掉换行符')
    for ssij in grafk:
        ssij = str(ssij).replace("\n", "")
        # ssij = str(ssij).replace(" ", "")
        # ssij = str(ssij).replace("　", "")
        if len(ssij)>0:
            aaby.append(ssij)

    # aaby=no_repeat_list(aaby)
    return aaby

def get_show_list(beginstr,filename,tetype):
    listaa2 = read_content_order22(filename)
    if tetype==0:
        listaa = []
        # 这里还要设置，要从哪一句话开始。
        for gbv in range(len(listaa2)):
            lljn = listaa2[gbv]
            if str(lljn).find(str(beginstr)) != -1:
                listaa = listaa2[gbv:]
                return listaa
    else:
        return listaa2

#编码成字典
def to_dict(filename):
    #不应该这样子读，应该是顺序读取
    ssa = read_content_order22(filename)
    kk=0
    dictu={}
    for jj in ssa:
        kk=kk+1
        dictu[kk]=jj
    return dictu

#写入json文件
def to_json_file(basc,filename):
    # ssa=read_content(filename)
    print(f'转换成json文件:{filename}')
    outfile=out_name2(basc,filename,'j',out="jsondata",back='json')
    ssdict=to_dict(filename)
    with open(outfile, 'w',encoding="utf-8") as write_f:
        json.dump(ssdict,write_f,indent=4, ensure_ascii=False)
    return outfile

#读取json文件
def get_jsonfile(jsonfile):
    print(f'获取json文件:{jsonfile}')
    with open(jsonfile, 'r',encoding="utf-8") as load_f:
        load_dict = json.load(load_f)
    return load_dict

def list_to_dict(list1):
    kk = 0
    dictu = {}
    for jj in list1:
        kk = kk + 1
        dictu[kk] = jj
    return dictu

# 字符写成json文件
def dict_to_json22(dict_ss, filename):
    print('字符写成json文件')
    json_data = json.dumps(dict_ss, ensure_ascii=False)
    with open(filename, 'w',encoding="utf-8") as f_six:
        f_six.write(json_data)

def list_to_jsonfile(list1,jsonfile):
    dict1=list_to_dict(list1)
    dict_to_json22(dict1, jsonfile)

#计算一行多少字符的计算器
def count_per_row_str_inlist(list1):
    bignum=0
    for llo in list1:
        numlen=len(llo)
        if numlen>bignum:
            bignum=numlen
    lena=bignum


    if lena>6:
        if lena==7:
            neas=3
        else:
            if lena>13:

                neas=1
            else:
                neas = 3
    else:
        neas=4
    return neas

#从数字替换格式中，转换成字典
def num_peop_to_dict(list1):
    pe_nmshuzu1 = {}

    # 字典列表，键的长度
    # lbzd = []

    # 提取出人物数字数组
    for y in list1:
        y = y.replace(" ", "")

        if y.find("，") != -1:
            dwz = y.find("，")
            dwza = int(dwz) + 1

            # 这是字典的值
            jqsz = str(y)[dwza:]
            jqsz = jqsz.replace(" ", "")
            jqsz = jqsz.replace("\n", "")
            # print(jqsz)
            # sys.exit()

            # 这里要获取字典的键
            jqszj = str(y)[0:dwz]
            jqszj = jqszj.replace(" ", "")
            jqszj = jqszj.replace("\n", "")
            # print(f'键：{jqszj}')
            pe_nmshuzu1[str(jqszj)] = str(jqsz)
    return pe_nmshuzu1

def se_every_file_in_normal(dirpath,file_type=None):
    file_list=[]
    files = os.listdir(dirpath)
    files = natsorted(files, alg=ns.PATH)
    if file_type is None:
        exte_type = '.txt'
    else:
        exte_type= f"{file_type}"
    for filename in files:
        exte_nam = os.path.splitext(filename)[1]
        if exte_nam:
            # print("后缀名存在")
            if file_type is None:
                if str(exte_type) == str(exte_nam):
                    aab = dirpath + '/' + filename
                    file_list.append(aab)
            else:
                aab = dirpath + '/' + filename
                file_list.append(aab)
                # get_last_name_from_file(aab)
    return file_list

#这是根据图片标签重命名图片的
#这是根据文件修改图片名的
def rename_pic_name(filter_text_file,origin_dir):
    fontfilelist_path = filter_text_file
    filelist1 = read_content_order233(fontfilelist_path)
    for pp in filelist1:
        point_place=str(pp).find(".")
        hou_zhui=str(pp)[int(point_place):int(point_place+4)]
        tag_begin_place=point_place+4
        tag_name=str(pp)[tag_begin_place:len(pp)]
        if str(tag_name).find("?")!=-1:
            tag_name=str(tag_name).replace("?","？")
        before_name=str(pp)[:point_place]
        outname=f"{before_name}{tag_name}{hou_zhui}"
        # print(outname)

        #原文件
        origin_pic_file_name=str(pp)[:int(point_place+4)]
        image_path = origin_dir + "/" + origin_pic_file_name
        rename_luj = origin_dir +"/" + outname

        os.rename(image_path, rename_luj)
    print("重命名完成！")
    return 1

#这书删掉一些图片名称的前缀之类的
def rename_pic_bef_name(origin_dir,bef_place=None):
    files = os.listdir(origin_dir)
    files = natsorted(files, alg=ns.PATH)
    for filename in files:
        exte_nam = os.path.splitext(filename)[1]
        if exte_nam:
            image_path = origin_dir + "/" + filename
            if bef_place is not None:
                outname=str(filename)[int(bef_place):]
                rename_luj = origin_dir + "/" + outname
                os.rename(image_path, rename_luj)
            else:
                print("请设定要截的前字符串\n程序退出")
                sys.exit()

#删掉不需要的时间戳
def drop_extra_timemark(pic_dir):
    files = os.listdir(pic_dir)
    files = natsorted(files, alg=ns.PATH)
    for filename in files:
        if str(filename).find("]")!=-1:

            point_place=str(filename).rfind(".")
            limit_right_sign=str(filename).rfind("]")
            if limit_right_sign==point_place-1:
                limit_left_sign = str(filename).rfind("[")
                outname=str(filename)[:limit_left_sign]
                exte_nam = os.path.splitext(filename)[1]
                rename_luj = pic_dir + "/" + outname+str(exte_nam)
                image_path = pic_dir + "/" + filename
                os.rename(image_path, rename_luj)
    print("不需要的时间戳，删除完成")


#裁剪缩小大量图片的
def reduce_pic_size(firedir):
    files = os.listdir(firedir)
    files = natsorted(files, alg=ns.PATH)

    #找到上一层的文件夹
    last_dir=os.path.dirname(firedir)
    dirname=os.path.basename(firedir)
    dirname=str(dirname).replace(".","")
    # print(last_dir)
    # print(dirname)
    # return
    # dirname=str(firedir)
    if not os.path.exists(f"{last_dir}/压缩的"):
        print("输出文件夹不存在，帮你自动创建好了")
        print("==================================")
        os.mkdir(f"{last_dir}/压缩的")
    if not os.path.exists(f"{last_dir}/压缩的/{dirname}_reduce"):
        print("输出文件夹不存在，帮你自动创建好了")
        print("==================================")
        os.mkdir(f"{last_dir}/压缩的/{dirname}_reduce")
    mm=0
    for filename in files:
        exte_nam = os.path.splitext(filename)[1]
        if exte_nam:
            mm=mm+1
            print(f"{mm}/{len(files)}")
            imagefile=firedir+"/"+filename
            im12 = Image.open(imagefile)
            width12, height12 = im12.size
            im13 = im12.resize((int(width12 // 1.7), int(height12 // 1.7)), Image.LANCZOS)
            # im13 = im13.convert("RGB")
            outname = f"{last_dir}/压缩的/{dirname}_reduce/{filename}"
            # outname.replace(".")
            # filename, suffix = os.path.splitext(background)
            im13.save(outname)
            # cv2.imwrite(outname, im13)

#重命名然后去掉不需要的时间戳
def rename_and_drop_timemark(pic_dir,timefile):
    whet_success=rename_pic_name(timefile, pic_dir)
    if whet_success==1:
        drop_extra_timemark(pic_dir)

#重命名为数字序列
def re_pic_num_name(firedir):
    files = os.listdir(firedir)
    files = natsorted(files, alg=ns.PATH)
    origin_dir=firedir
    ss=0
    for filename in files:
        exte_nam = os.path.splitext(filename)[1]
        if exte_nam:

            ss=ss+1
            image_path = origin_dir + "/" + filename
            rename_luj =f"{origin_dir}/{ss}{exte_nam}"
            os.rename(image_path, rename_luj)







if __name__ == '__main__':

    firedir="F:/"
    # firedir=f"{BASC}/image1"
    re_pic_num_name(firedir)
    pass